package com.java.recursive;

/**
 * 斐波那契数列
 * @author 19252
 * @date 2020/7/15
 */
public class Demo {

    public static void main(String[] args) {
        Demo demo = new Demo();
        System.out.println(demo.fun(6));
    }

    public int fun(int n) {
        if (n <= 0){
            return 0;
        }
        if (n < 2){
            return 1;
        }
        return fun(n - 1) + fun(n - 2);
    }

    /**
     * 对递归求解斐波那契数列的优化
     */
    public int funBetter(int n) {
        int[] result = new int[40];
        result[0] = 0;
        result[1] = 1;
        result[2] = 1;
        if (n > 2) {
            for (int i = 2; i <= n; i++) {
                result[i] = result[i - 1] + result[i -2];
            }
        }
        return result[n];
    }
}
